<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * 
 */
class Thirdparty extends CI_Controller {
	private $token_user; 	// token key from redis
	private $tid;	// user tid
	private $token; // thirdparty token

	public function __construct(){
		parent::__construct();
		session_start();
		$this->load->helper("common");


		$this->token = $this->input->post('token');

	}

	/**
	 * auth page
	 * @return [type] [description]
	 */
	public function auth($act=''){
		// is third party available?
		$this->_check_cooperation($act);

		$key =  md5('auth' + time());
		$data['auth_key'] = $key;
		$data['auth_name'] = $act;
		$_SESSION['auth_check'] = $key;
		$this->load->view('thirdparty_auth',$data);
	}

	/**
	 * auth check
	 * @return [type] [description]
	 */
	public function auth_do(){
		// need to be a post request
		if(!(strtolower($_SERVER['REQUEST_METHOD']) == 'post') ){
			json_return(false,'need to be a post request');
		}

		$auth_name = $this->input->post('auth_name');
		
		// post form safe check
		$this->_check_auth_key();

		// is third party available?
		$this->_check_cooperation($auth_name);

		// set redis key for auth
		$this->token_user =  md5($this->input->post('auth_name') . $this->input->post('email').md5($this->input->post('password')));

		// 1. check for redis cache
		if($this->config->item('cache_on') && $token = cache_get($this->token_user)){
			json_return(true,array('token'=>$token));
		}

		// 2. check from DB
		$this->_check_from_db();

		// 3. check from epiid api
		$this->_check_from_epiid();

		json_return(false,"auth faild, invalid email or password");

	}

	/**
	 * get sport data
	 * @return [type] [description]
	 */
	public function getdata(){
		// need to be a post request
		if(!(strtolower($_SERVER['REQUEST_METHOD']) == 'post') ){
			json_return(false,'need to be a post request');
		}

		$this->_check_cooperation($this->input->post('flag'));

		$this->_checktoken_from_db();

		$date 	= $this->input->post('date');
		// $id 	= $this->input->post('id');
		$unit 	= $this->input->post('unit');

		$unit_option = array('week','day','month','year','all');

		if($unit != 'all' && !$date){
			json_return(false,'request POST date');
		}
		$unit = $unit ? $unit : 'week';
		$unit = strtolower($unit);
		// not a valid unit
		if(!in_array($unit,$unit_option)){
			json_return(false,'invalid unit');
		}




		// get cache
		// redis key for get data
		$key = md5($this->input->post('token').$date.$unit);
		if($this->config->item('cache_on') &&  $data = cache_get($key)){
			cache_flush();
			$data = jsonObj_to_array(json_decode($data));
		}else{
			$this->load->model('user_data');
			$array = array('tid'=>$this->tid,'date'=>$date);
			// var_dump($array);die;
			$data  = $this->user_data->getUserData($array,$unit);
			if($this->config->item('cache_on')){
				cache_set($key,json_encode($data));
			}
		}

		if(!empty($data['data']) && is_array($data['data'])){
			$data['success'] = true;
			echo json_encode($data);
			exit;
		}else{
			// no data
			json_return(false,'no data');
		}
	}
/****************************************************************************************/
/********************************private function********************************************/
/****************************************************************************************/
	private function _save_to_db($data){
		// var_dump($data);die;
		$insert = array(
			'third_name'=>$this->input->post('auth_name'),
			'token'=>$data->token,
			'email'=>$data->email,
			'tid'=>$data->tid,
			'password'=>md5($this->input->post('password'))
			);
		$this->load->model('user_thirdparty');
		$db = $this->user_thirdparty->db;
		$db->insert('user_thirdparty',$insert);
		// var_dump($db->affected_rows());
	}

	private function _save_to_redis($token){
		if($this->config->item('cache_on') ){
			cache_set($this->token_user,$token,3600*24);
		}
	}

	private function _get_tid($token){
			// get tid
			$apiUrl = $this->config->item('token_check_api');

			$info = post($apiUrl,array('usertoken'=>$token));
			// var_dump($info);die;
			$info = json_decode($info);
			if(isset($info->success) && $info->success == true){
				return $info->id;
			}

			return '';
	}
	private function _check_from_epiid(){
		$data = array(
			'user'=>array(
				'email'=>$this->input->post('email'),
				'password'=>$this->input->post('password')
				)
			);
		$url = $this->config->item('login_api');
		$rs = post($url,$data);
		$rs = json_decode($rs);
		if($rs->success && $rs->token){

			$rs->tid = $this->_get_tid($rs->token);

			// create a third party token
			$rs->token = md5($this->input->post('auth_name') .  '_' .$rs->token);
			$this->_save_to_db($rs);
			$this->_save_to_redis($rs->token);

			$this->tid = $rs->tid;
			$this->token = $rs->token;

			json_return(true,array('token'=>$rs->token));
		}
	}
	// check for auth
	private function _check_from_db(){
		$this->load->model('user_thirdparty');
		$db = $this->user_thirdparty->db;
		$email = $this->input->post('email');
		$where = array('email'=>$email,'password'=>md5($this->input->post('password')),'status'=>1,'third_name'=>$this->input->post('auth_name'));
		$rs = $db->get_where('user_thirdparty',$where)->row_array();

		if($db->affected_rows()){
			$this->_save_to_redis($rs['token']);
			$this->tid = $rs['tid'];
			$this->token = $rs['token'];

			json_return(true,array('token'=>$rs['token']));
		}
	}

	// check for data handle
	private function _checktoken_from_db(){
		$this->load->model('user_thirdparty');
		$db = $this->user_thirdparty->db;
		$rs = $db->get_where('user_thirdparty',array('token'=>$this->token))->row_array();
		if(!$db->affected_rows()){
			json_return(false,"permmision deny");
		}
		$this->tid = $rs['tid'];
	}

	private function _check_auth_key(){
		$auth_key = isset($_POST['auth_key'])?$_POST['auth_key'] : '';
		$key = $_SESSION['auth_check'];
		if(!$auth_key || !($auth_key==$key)) json_return(false,"invalid request");

	}

	private function _check_cooperation($act){
		
		$third_cooperations = $this->config->item('third_cooperations');
		if(!in_array($act, $third_cooperations)) json_return(false,'bad request');
	}
}